<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use app\models\Article;

class CategoryController extends Controller{

    public function actionTree(){
        $arr=array();

        $connection = Yii::$app->db;
        $sql = "SELECT * FROM tbl_category WHERE parent = 0 ORDER BY `order` ASC";
        $rootFolderList = $connection->createCommand($sql)->queryAll();

        if (is_array($rootFolderList) && (sizeof($rootFolderList)>0)){

            foreach($rootFolderList as $rootFolderItem){
                $da = array(
                    "id" => $rootFolderItem['id'],
                    "name"=> $rootFolderItem['name'],
                    "url"=> "index.php?r=article/listbycategory&categoryid=".$rootFolderItem['id'],
                    "target"=>"rightframe",
                    "children"=> $this->GetChildren($rootFolderItem['id'])
                );
                array_push($arr,$da);
            }
        }
        return (json_encode($arr));
    }

    private function GetChildren($categoryid){

        $connection = Yii::$app->db;
        $sql = "SELECT * FROM tbl_category WHERE parent = $categoryid ORDER BY `order` ASC";
        $subCategoryList = $connection->createCommand($sql)->queryAll();

        if (is_array($subCategoryList) && (sizeof($subCategoryList) > 0)){
            $data = array();

            foreach($subCategoryList as $subCategoryItem){
                $da = array(
                    "id" => $subCategoryItem['id'],
                    "name"=>$subCategoryItem['name'],
                    "url"=> "index.php?r=article/listbycategory&categoryid=".$subCategoryItem['id'],
                    "target"=>"rightframe",
                    "children"=>$this->GetChildren($subCategoryItem['id'])
                );
                array_push($data,$da);
            }
            return $data;
        }else{
            return null;
        }
    }
}